package studio.xiaoyun.core.parameter.criterion;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import studio.xiaoyun.core.exception.CoreException;
import studio.xiaoyun.core.parameter.Parameter;

public class CriterionIn extends Criterion {
	private static final long serialVersionUID = 2804155591787340132L;
	private String propertyName;
	private Collection<?> values;

	protected CriterionIn(String propertyName, Collection<?> values) {
		this.propertyName = propertyName;
		this.values = values;
	}

	@Override
	public List<String> getPropertyName() {
		return Arrays.asList(propertyName);
	}

	@Override
	public String getQuery(Parameter parameter) {
		StringBuffer result = new StringBuffer("%s in (");
		DataType dataType = this.getDataType(parameter, propertyName);
		for(Object value:values){
			switch (dataType) {
			case DATE:
				result.append("'");
				if (value instanceof Date) {
					result.append(this.formatDate((Date) value));
				} else {
					result.append(value.toString());
				}
				result.append("'");
				break;
			case NUMBER:
				result.append("").append(value.toString());
				break;
			case STRING:
				result.append("'").append(value.toString()).append("'");
				break;
			case ENUM:
				Object obj = value;
				Object objValue = null;
				if(!value.getClass().isEnum()){
					Class<?> type = this.getFieldByName(parameter, propertyName).getType();
					try{
						Method method = type.getMethod("valueOf", String.class);
						obj = method.invoke(null, value.toString());
					}catch(Exception e){
						throw new CoreException(type.getName()+"中没有定义"+value.toString());
					}
				}
				try{
					objValue = obj.getClass().getMethod("value").invoke(obj);
				}catch(Exception e){
					objValue = obj.toString();
				}
				if(objValue.getClass() == Integer.TYPE || objValue.getClass() == Integer.class){
					result.append("").append(objValue.toString());
				}else{
					result.append("'").append(objValue.toString()).append("'");
				}
				break;
			default:
				throw new CoreException("属性" + propertyName + "不支持In");
			}
			result.append(",");
		}
		result.deleteCharAt(result.length()-1);
		result.append(")");
		return result.toString();
	}

}
